package com.imooc.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//@Component
public class TimeInterceptor implements HandlerInterceptor{
	
	/**
	 * 方法执行之前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest requset, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("preHandle");
		long start = new Date().getTime();
		requset.setAttribute("startTime", start);
		return true;
	}

	/**
	 * 方法执行之后（没有出现异常的情况下）
	 */
	@Override
	public void postHandle(HttpServletRequest requset, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("postHandle");
		Long start = (Long)requset.getAttribute("startTime");
		System.out.println("耗时：" + (new Date().getTime() - start));
	}

	/**
	 * 方法执行之后，渲染页面之前（有没有出现异常都会调用）
	 */
	@Override
	public void afterCompletion(HttpServletRequest requset, HttpServletResponse response, Object arg2, Exception e)
			throws Exception {
		System.out.println("afterCompletion");
		Long start = (Long)requset.getAttribute("startTime");
		System.out.println("耗时：" + (new Date().getTime() - start));
		System.out.println("exception is " + e);
	}
}
